<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>接龙展示 - 使用插件 - 自定义节点</title>
    <script src="./lib/g6.js"></script>
    <script src="./lib/plugins.js"></script>
    <script src="./data.js"></script>
    <style>
      #mountNode {
        border: 1px solid #ccc;
      }
      .node {
        border: 1px solid red;
        width: 100px;
        height: 100px;
        box-sizing: border-box;
        font-size: 12px;
      }
    </style>
  </head>
  <body>
    <div id="mountNode"></div>
    <button id="refresh">refresh</button>
    <script>
      const graph = new G6.Graph({
        container: "mountNode",
        height: 800,
        renderer: "svg",
        fitView: "lc",
        layout: new G6.Layouts["Dagre"]({
          rankdir: "LR"
        }),
        modes: {
          default: ["panCanvas", "wheelZoom"]
        }
      });
      G6.registerNode("customNode", {
        draw(item) {
          const group = item.getGraphicGroup();
          const model = item.getModel();
          const html = G6.Util.createDOM(`<div class="node">
             ${model.id} <br> ${model.time}
          </div>`);
          return group.addShape("dom", {
            attrs: {
              x: 0,
              y: 0,
              width: 100,
              height: 100,
              html
            }
          });
          return group;
        },
        anchor(item) {
          return [[0, 0.5], [1, 0.5]];
        }
      });
      graph.node({
        shape: "customNode"
      });
      graph.edge({
        shape: "polyline-round", // 'quadraticCurve',
        style: {
          stroke: "#666",
          lineWidth: 1,
          strokeOpacity: 1,
          endArrow: true
        }
      });
      graph.on("node:click", ev => {
        console.log(ev);
        let model = ev.item.getModel();
        console.log(model);
        alert(model.id);
      });
      graph.read(data);
      document.querySelector("#refresh").addEventListener("click", () => {
        data.nodes = data.nodes.map(item => {
          item.time = Date.now();
          return item;
        });
        console.log(data.nodes);
        // graph.read(data);
        refresh(data);
      });
      function refresh(data) {
        const ev = {
          action: "changeData",
          data
        };
        graph.emit("beforechange", ev);
        graph.clear();
        graph.source(data);
        graph.render();
        graph.emit("afterchange", ev);
      }
    </script>
  </body>
</html>
